# -*- coding: utf-8 -*-
import random, os, json, time, sys , xlwt ,re
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import tkinter as tk
import tkinter.font as font
from tkinter import messagebox
import threading


class Gui:
    def __init__(self):
        self.root=tk.Tk()
        self.root.title("淘宝SKU价格获取")
        self.root.geometry("800x600+550+200")
        self.root.resizable(False, False)
        self.root.configure(bg="LightSkyBlue")
        self.tkbuju()
        self.root.mainloop()

    def tkbuju(self):
        path =self.jianchacooie(1)
        self.font_2 = font.Font(family='Arial', size=15, weight='bold')
        self.wenben2 = tk.Label(self.root,width=68,height=3,foreground="red",font=self.font_2,text=path)
        self.wenben2.grid(row=1,columnspan=3)
        self.wenben3=tk.Text(self.root,width=84,height=5,relief=tk.RAISED,bd=2)
        self.wenben3.grid(row=2, column=0)
        self.button1 = tk.Button(self.root, width=15, height=4, text="登录",command=self.button11)
        self.button1.grid(row=2, column=1)
        self.button2=tk.Button(self.root,width=15,height=4,text="获取价格",command=self.huoqusearces)
        self.button2.grid(row=2,column=2)
        self.wenben4 = tk.Text(self.root, width=117, height=50, relief=tk.RAISED, bd=2)
        self.wenben4.grid(row=3, columnspan=3)

    def button11(self):
        t=threading.Thread(target=self.jianchacooie,args=(0,))
        t.start()
        # self.jianchacooie(0)

    def jianchacooie(self,numm):
        if numm==0:
            Chrome().huoqucookie(1)
        path=os.getcwd()
        self.font_2 = font.Font(family='Arial', size=15, weight='bold')
        if os.path.isdir(path+"/taobaocookie"):
            summ=[]
            for root,dirs,files in os.walk(path+"/taobaocookie"):
                for file in files:
                    summ.append(file)
            if len(summ)>0:
                self.wenben2 = tk.Label(self.root, width=68, height=3, foreground="red", font=self.font_2,
                                        text="请在下方输入需要搜索的内容，多个以逗号(,)分割------------------例:xiaomi,mate")
                self.wenben2.grid(row=1, columnspan=3)
                return "请在下方输入需要搜索的内容，多个以逗号(,)分割------------------例:xiaomi，mate"

            else:
                self.wenben2 = tk.Label(self.root, width=68, height=3, foreground="red", font=self.font_2,
                                        text="当前没有账号可用于登录淘宝，请先点击登录按钮")
                self.wenben2.grid(row=1, columnspan=3)
                return "当前没有账号可用于登录淘宝，请先点击登录按钮"


        else:
            self.wenben2 = tk.Label(self.root, width=68, height=3, foreground="red", font=self.font_2,
                                    text="当前没有账号可用于登录淘宝，请先点击登录按钮")
            self.wenben2.grid(row=1, columnspan=3)
            return "当前没有账号可用于登录淘宝，请先点击登录按钮"


    def huoqusearces(self):
        a=self.wenben3.get("1.0",tk.END)
        a=a.replace('，',',')
        seacres=a.strip().split(",")
        ifdelu=Chrome().readcookie()
        if ifdelu==0:
            messagebox.showwarning("警告","请先登录")
        else:
            self.wenben4.delete("1.0",tk.END)
            self.wenben4.insert(tk.END,f"开始获取{seacres}价格\n")
            Chrome().searceliulanqi(seacres)
            self.wenben4.insert(tk.END, f"获取{seacres}价格完成\n")



class Chrome:
    def liulanihead(self):
        server = Service(executable_path=r'软件\chromedriver.exe')
        opt = Options()
        # heads = [
        #     "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.12",
        #     "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/512.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/111.12",
        #     "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/457.36 (KHTML, like Gecko) Chrome/98.0.0.0 Safari/123.24",
        #     "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/597.36 (KHTML, like Gecko) Chrome/68.0.0.0 Safari/127.98",
        #     "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/137.36 (KHTML, like Gecko) Chrome/93.0.0.0 Safari/127.98",
        #     "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/267.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36 Edg/134.0.0.0",
        #     "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/387.36 (KHTML, like Gecko) Chrome/98.0.0.0 Safari/537.36 Edg/98.0.1.0",
        #     "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/497.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.2.9.0",
        #     "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/517.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36 Edg/76.4.1.1"
        # ]
        # head = random.choice(heads)
        # opt.add_argument(f'--user-agent={head}')
        opt.add_argument("--disable-blink-features=AutomationControlled")  # 关闭自动化控制特征
        opt.add_experimental_option("excludeSwitches", ["enable-automation"])  # 隐藏顶部警告栏
        opt.add_experimental_option("useAutomationExtension", False)  # 禁用自动化扩展
        return server, opt

    def huoqucookie(self, num):
        server, opt = self.liulanihead()
        taobao = webdriver.Chrome(service=server, options=opt)
        taobao.maximize_window()
        taobao.get('https://s.taobao.com/search?')
        time.sleep(random.uniform(1, 2))
        denglutaobao = taobao.find_element(By.XPATH, '/html/body/div[1]/div/ul[1]/li[2]/div[1]/div[1]/a[1]')
        denglutaobao.click()
        time.sleep(random.uniform(15, 20))
        cookie = taobao.get_cookies()
        taobao.quit()
        self.savecookie(cookie, num)


    def searceliulanqi(self,searces):
        cookies = self.readcookie()
        server, opt = self.liulanihead()
        taobao = webdriver.Chrome(service=server, options=opt)
        taobao.maximize_window()
        taobao.get('https://s.taobao.com/search?')
        time.sleep(random.uniform(1, 2))
        for i in cookies:
            taobao.add_cookie(i)
        time.sleep(random.uniform(1.5, 2))
        for searce in searces:
            jss = 0
            datalist = []
            taobao.refresh()
            searcetxt = taobao.find_element(By.CSS_SELECTOR, '.search-suggest-combobox-imageSearch-input')
            time.sleep(random.uniform(0.5, 3))
            searcetxt.send_keys(Keys.CONTROL + "a")
            time.sleep(random.uniform(0.5, 2.5))
            searcetxt.send_keys(Keys.DELETE)
            time.sleep(random.uniform(0.5, 1))
            searcetxt.send_keys(searce)
            time.sleep(random.uniform(1.5, 2.5))
            searcebutton = taobao.find_element(By.CSS_SELECTOR, '.btn-search')
            searcebutton.click()
            time.sleep(random.uniform(1.5, 2.5))
            searcesaixuan = taobao.find_element(By.XPATH, '/html/body/div[3]/div[3]/div[1]/div/div/div[2]/div[2]/div[1]/div[1]/div/div[1]/div/div/div/ul/li[2]/div')
            searcesaixuan.click()
            time.sleep(random.uniform(5, 6))
            dangpinglist = taobao.find_elements(By.CSS_SELECTOR, '.title--qJ7Xg_90')
            try:
                for i in dangpinglist:
                    data = []
                    if jss > 10:
                        break
                    i.click()
                    time.sleep(random.uniform(1.5, 2.5))
                    taobao.switch_to.window(taobao.window_handles[1])
                    js = 'window.scrollTo({top: 300,behavior: "smooth" });'
                    js1 = 'document.querySelector(".NormalFixedInfo--Fy4wn7vY").style.display="block";'
                    js2 = 'document.querySelector(".NormalFixedInfo--Fy4wn7vY").style.opacity="1";'
                    time.sleep(random.uniform(2, 3))
                    taobao.execute_script(js)
                    time.sleep(random.uniform(1.5, 2.5))
                    taobao.execute_script(js1)
                    taobao.execute_script(js2)
                    time.sleep(random.uniform(1.5, 2.5))
                    try:
                        dianpuming = taobao.find_element(By.CSS_SELECTOR, '.shopName--mTDZGIPO').text
                    except Exception:
                        dianpuming="天猫超市"
                        shangpingmiaoshu='无'
                        skujiagetxt="无"
                        data.append(dianpuming)
                        data.append(shangpingmiaoshu)
                        data.append(skujiagetxt)
                        datalist.append(data)
                        taobao.close()
                        taobao.switch_to.window(taobao.window_handles[0])
                        time.sleep(random.uniform(2.5, 3.5))
                        continue
                    shangpingmiaoshu = taobao.find_element(By.CSS_SELECTOR, '.mainTitle--O1XCl8e2.f-els-2').text
                    data.append(dianpuming)
                    data.append(shangpingmiaoshu)
                    skus = taobao.find_elements(By.CSS_SELECTOR, '.content--TiXrAN07')
                    sku1 = None
                    sku2 = None
                    if len(skus) == 2:
                        for i in skus:
                            if skus.index(i) == 0:
                                sku1 = i
                            if skus.index(i) == 1:
                                sku2 = i
                    else:
                        for i in skus:
                            if skus.index(i) == 0:
                                sku1 = i
                    if sku1 and sku2:
                        datas = []
                        for i in sku1.find_elements(By.CSS_SELECTOR, '.valueItem--GzWd2LsV'):
                            if 'isDisabled--x_T2h1sh' not in sku1.get_attribute('class'):
                                sku1name = i.text
                                i.click()
                                time.sleep(random.uniform(2, 7))
                                for ii in sku2.find_elements(By.CSS_SELECTOR, '.valueItem--GzWd2LsV'):
                                    if 'isDisabled--x_T2h1sh' not in sku1.get_attribute('class'):
                                        sku2name = ii.text
                                        ii.click()
                                        time.sleep(random.uniform(1, 8))
                                        skujiage = taobao.find_element(By.CSS_SELECTOR, '.highlightPrice--OOP9oDP8')
                                        skujiagetxt = skujiage.text
                                        datas.append(sku1name)
                                        datas.append(sku2name)
                                        datas.append(skujiagetxt)
                                        datas.append('，')
                        data.append(datas)
                    if sku1:
                        datas = []
                        for i in sku1.find_elements(By.CSS_SELECTOR, '.valueItem--GzWd2LsV'):
                            if 'isDisabled--x_T2h1sh' not in sku1.get_attribute('class'):
                                sku1name = i.text
                                i.click()
                                time.sleep(random.uniform(2, 10))
                                skujiage = taobao.find_element(By.CSS_SELECTOR, '.highlightPrice--OOP9oDP8')
                                skujiagetxt = skujiage.text
                                datas.append(sku1name)
                                datas.append(skujiagetxt)
                                datas.append('，')
                        data.append(datas)
                    datalist.append(data)
                    taobao.close()
                    taobao.switch_to.window(taobao.window_handles[0])
                    time.sleep(random.uniform(10, 60))
                    jss += 1
            finally:
                Savexls().savexls(datalist,searce)

        taobao.quit()

    def savecookie(self, cookie, num):
        if os.path.isdir('taobaocookie'):
            pass
        else:
            os.mkdir('taobaocookie')
        with open(fr'taobaocookie\cookie{num}', 'w', encoding='utf-8') as f:
            json.dump(cookie, f, indent=4, ensure_ascii=False)


    def readcookie(self):
        cookiefiles = []
        for root, dirs, files in os.walk('taobaocookie'):
            for file in files:
                cookiefiles.append(os.path.join(root, file))
        if cookiefiles:
            with open(random.choice(cookiefiles)) as f:
                cookies = json.load(f)
                return cookies
        else:
            return 0

class Savexls:
    def savexls(self, data, saveming):
        save = xlwt.Workbook(encoding='utf-8')
        tb = save.add_sheet('sheet1',cell_overwrite_ok=True)
        for x in range(0,len(data)):
            for y in range(0,3):
                if y==2:
                    list=[]
                    for iii in data[x][y]:
                        iii=re.sub(r'\n','',iii)
                        list.append(iii)
                    tb.write(x,y,list)
                else:
                    tb.write(x,y,data[x][y])
        save.save(f'{saveming}.xls')


if __name__=='__main__':
    start= Gui()